package com.jf.memory.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.memory.repository.jdbc.JdbcChatMemoryRepository;
import org.springframework.ai.chat.memory.repository.jdbc.MysqlChatMemoryRepositoryDialect;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import javax.sql.DataSource;
import java.util.UUID;

/**
 * @author Jflame
 * @version 1.0.0
 * @since 2025/8/14
 */
@RestController
public class MemoryController {
    private ChatClient chatClient;

    public MemoryController(ChatClient.Builder builder, DataSource dataSource) {
        JdbcChatMemoryRepository memoryRepository = JdbcChatMemoryRepository
                .builder()
                .dataSource(dataSource)
                .build();
        ChatMemory chatMemory = MessageWindowChatMemory.builder().chatMemoryRepository(memoryRepository).build();
        this.chatClient = builder
                .defaultAdvisors(MessageChatMemoryAdvisor
                        .builder(chatMemory)
                        .build())
                .build();
    }

    @GetMapping(value = "/memory" , produces = "text/html;charset=UTF-8")
    public Flux<String> memory(@RequestParam(value = "message") String message, @RequestParam(value = "conversation_id") String conversationId) {
        return chatClient.prompt().user(message).advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId)).stream().content();
    }
    @GetMapping("/id")
    public String id() {
        return UUID.randomUUID().toString();
    }
}
